package com.craftplay.service;


import com.craftplay.dao.CollectionMapper;
import com.craftplay.dao.UnitMapper;
import com.craftplay.model.BehaveModel;
import com.craftplay.model.Collection;
import com.craftplay.model.Unit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CollectionService {

    @Autowired
    private CollectionMapper collectionMapper;

    @Autowired
    private BehaveService behaveService;

    @Autowired
    private UnitMapper unitMapper;


    /**
     * 关注数量
     *
     * @param userId
     * @return
     */
    public int focusMyUserNum(int userId) {
        return collectionMapper.selectByUserIdNum(userId);
    }

    /**
     * 新增收藏
     *
     * @param collection
     * @return
     */
    public int addCollection(Collection collection) {
        if (!isCollection(collection.getUserId(), collection.getUnitId())) {
            Unit unit = unitMapper.selectByPrimaryKey(collection.getUnitId());
            if (unit == null) {
                return 0;
            }
            BehaveModel behaveModel = new BehaveModel();
            behaveModel.setUserId(unit.getUserId());
            behaveModel.setBuserId(collection.getUserId());
            behaveModel.setUnitId(collection.getUnitId());
            behaveModel.setBehave("收藏");
            behaveModel.setCreateTime(new Date());
            behaveService.insertBehave(behaveModel);
            return collectionMapper.insert(collection);
        }
        return 1;

    }


    /**
     * 取消收藏
     *
     * @param collection
     * @return
     */
    public int delCollection(Collection collection) {
        return collectionMapper.deleteByUserId(collection);
    }


    /**
     * 是否收藏
     *
     * @param userId
     * @param unitId
     * @return
     */
    public boolean isCollection(int userId, int unitId) {
        List<Collection> collections = collectionMapper.selectByUserIdAndUnitId(userId, unitId);
        if (collections == null || collections.size() == 0) {
            return false;
        }
        return true;
    }


    /**
     * 收藏数量
     *
     * @param unitId
     * @return
     */
    public Integer collectionNum(int unitId) {
        List<Collection> collections = collectionMapper.selectByUnitId(unitId);
        return collections.size();
    }


    /**
     * 我的收藏
     *
     * @param userId
     * @return
     */
    public List<Collection> getMyCollection(Integer userId) {
        return collectionMapper.getMyCollection(userId);
    }
}
